import { ref, reactive, computed, watch } from 'vue';

/**
 * 表单模态框Hook - 用于与FormModal组件配合使用
 * @param {Object} options 配置选项
 * @returns {Object} 表单模态框相关状态和方法
 */
export function useFormModal(options = {}) {
  const {
    defaultForm = {}, // 默认表单数据
    rules = {}, // 表单验证规则
    title = '', // 模态框标题
    onSubmit = null, // 提交回调
    onCancel = null, // 取消回调
    beforeOpen = null, // 打开前回调
    afterClose = null, // 关闭后回调
    formItems = [], // 表单项配置
    submitText = '确定', // 提交按钮文字
    cancelText = '取消', // 取消按钮文字
    width = 520, // 模态框宽度
    formLayout = 'horizontal', // 表单布局
    labelCol = { span: 6 }, // 标签列配置
    wrapperCol = { span: 18 }, // 包装列配置
    autoResetForm = true, // 自动重置表单
    validateOnRules = true, // 是否基于规则验证
    transformSubmitData = null, // 提交数据转换函数
  } = options;

  // 状态
  const visible = ref(false);
  const formState = reactive({...defaultForm});
  const formRules = reactive({...rules});
  const modalTitle = ref(title);
  const loading = ref(false);
  const isEdit = ref(false);
  const currentRecord = ref(null);
  
  // 当前表单项
  const currentFormItems = ref([...formItems]);
  
  // 模态框配置
  const modalProps = reactive({
    width,
    cancelText,
    okText: submitText,
    destroyOnClose: true,
  });
  
  // 表单配置
  const formProps = reactive({
    layout: formLayout,
    labelCol,
    wrapperCol,
  });
  
  // 打开模态框
  const open = (record = null, customTitle = null) => {
    // 调用打开前回调
    if (beforeOpen && typeof beforeOpen === 'function') {
      const result = beforeOpen(record);
      if (result === false) return; // 允许拦截打开
    }
    
    // 记录当前记录
    currentRecord.value = record;
    
    // 设置编辑状态
    isEdit.value = !!record;
    
    // 设置标题
    modalTitle.value = customTitle || (isEdit.value ? '编辑' : '新增');
    
    // 重置表单
    if (autoResetForm) {
      resetForm();
    }
    
    // 如果有记录，填充表单
    if (record) {
      Object.keys(formState).forEach(key => {
        if (record[key] !== undefined) {
          formState[key] = record[key];
        }
      });
    }
    
    // 显示模态框
    visible.value = true;
  };
  
  // 关闭模态框
  const close = () => {
    visible.value = false;
    
    // 调用关闭后回调
    if (afterClose && typeof afterClose === 'function') {
      afterClose(currentRecord.value);
    }
  };
  
  // 重置表单
  const resetForm = () => {
    // 重置为默认值
    Object.keys(formState).forEach(key => {
      formState[key] = defaultForm[key] !== undefined ? defaultForm[key] : undefined;
    });
    
    // 重置编辑状态
    isEdit.value = false;
    currentRecord.value = null;
  };
  
  // 处理提交
  const handleSubmit = async (values) => {
    if (!onSubmit) return;
    
    loading.value = true;
    
    try {
      // 转换提交数据
      const submitData = transformSubmitData 
        ? transformSubmitData(values, isEdit.value, currentRecord.value) 
        : values;
      
      // 调用提交回调
      await onSubmit(submitData, isEdit.value, currentRecord.value);
      
      // 关闭模态框
      close();
    } catch (error) {
      console.error('表单提交出错:', error);
    } finally {
      loading.value = false;
    }
  };
  
  // 处理取消
  const handleCancel = () => {
    // 调用取消回调
    if (onCancel && typeof onCancel === 'function') {
      onCancel();
    }
    
    // 关闭模态框
    close();
  };
  
  // 更新表单项
  const setFormItems = (items) => {
    currentFormItems.value = [...items];
  };
  
  // 更新表单规则
  const setFormRules = (rules) => {
    Object.keys(formRules).forEach(key => {
      delete formRules[key];
    });
    
    Object.keys(rules).forEach(key => {
      formRules[key] = rules[key];
    });
  };
  
  // 更新模态框标题
  const setModalTitle = (title) => {
    modalTitle.value = title;
  };
  
  return {
    // 状态
    visible,
    formState,
    formRules,
    loading,
    modalTitle,
    isEdit,
    currentRecord,
    currentFormItems,
    modalProps,
    formProps,
    
    // 计算属性
    formModalProps: computed(() => ({
      visible: visible.value,
      title: modalTitle.value,
      confirmLoading: loading.value,
      ...modalProps,
    })),
    
    // 方法
    open,
    close,
    resetForm,
    handleSubmit,
    handleCancel,
    setFormItems,
    setFormRules,
    setModalTitle,
  };
} 